package com.atguigu.gmall.index.controller;

import com.atguigu.gmall.common.bean.ResponseVo;
import com.atguigu.gmall.index.service.IndexService;
import com.atguigu.gmall.pms.entity.CategoryEntity;
import io.swagger.annotations.ApiOperation;
import org.redisson.api.*;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Controller
@RequestMapping("/")
public class IndexController {
    @Resource
    IndexService indexService;
    @GetMapping(value = {"/" , "/index.html"})
    public String index(Model model){
        //查询categories 首页需要获取展示
        //查询 一级商品分类数据：pms
        List<CategoryEntity> categoryEntities = indexService.getLevelOneCategories();
        model.addAttribute("categories",categoryEntities);
        return "index";
    }
    @Resource
    RedissonClient redissonClient;

    @ResponseBody
    @GetMapping("/index/a")
    public ResponseVo indexA() throws InterruptedException {
//        RLock lock = redissonClient.getLock("test:lock");
//        lock.lock(20 , TimeUnit.SECONDS);//获取一个锁 20s后过期

//        RReadWriteLock rwlock = redissonClient.getReadWriteLock("anyRWLock");
//        rwlock.writeLock().lock(20,TimeUnit.SECONDS);

        //开房间接口
        RCountDownLatch rdl = redissonClient.getCountDownLatch("room:666");
        //初始化
        if(!rdl.isExists()){
            rdl.trySetCount(4L);
        }
        System.out.println("创建666房间成功：等待玩家加入....");
        rdl.await();//阻塞等待
        System.out.println("房间已满，开始游戏....");
        return ResponseVo.ok("a..");
    }
    @ResponseBody
    @GetMapping("/index/b")
    public ResponseVo indexB(){
//        RLock lock = redissonClient.getLock("test:lock");
//        lock.lock(20 , TimeUnit.SECONDS);//获取一个锁 20s后过期

//        RReadWriteLock rwlock = redissonClient.getReadWriteLock("anyRWLock");
//        rwlock.readLock().lock();
        RCountDownLatch rdl = redissonClient.getCountDownLatch("room:666");
        rdl.countDown();
        System.out.println("加入666房间成功,等待游戏开始....");
//        rwlock.readLock().unlock();
        return ResponseVo.ok("b..");
    }
    @ResponseBody
    @GetMapping("/index/testLock")
    public ResponseVo testLock(){
        indexService.testLock();
        return ResponseVo.ok();
    }

    ///index/cates/
    @ResponseBody
    @ApiOperation("异步加载二三级商品分类")
    @GetMapping("/index/cates/{cid}")
    public ResponseVo loadLevel23Cates(@PathVariable("cid")Long cid){
        List<CategoryEntity> categoryEntities =indexService.loadLevel23Cates(cid);
        return ResponseVo.ok(categoryEntities);
    }
}
